"""
此文件为创建单点登录数据的方法
"""
import re
import requests

from common.get_env_config import GetURL
from common.get_log import log
from common.read_config import ReadOtherConfig


class CreatSingleloginData:
    r = requests.session()
    url = GetURL()
    config = ReadOtherConfig()

    def __init__(self):
        self.roottoken = self.get_singletoken(self.config.get_config_value('account_info', 'root_username'),
                                              self.config.get_config_value('account_info', 'root_password'))

    def get_singletoken(self, username, password):
        """
        此方法为获取单点登录的token,只适用单点登录
        :param username:
        :param password:
        :return:
        """
        # 打开单点登录页面
        LoginSinglePage_Resp = self.r.get(self.url.geturl1('/login'))
        # 获取登录页面隐藏的session
        sessionpattern = '<input\s+?type="hidden"\s+?name="_csrf"\s+?value="(.*?)"\s+?/>'
        csrf = re.findall(sessionpattern, LoginSinglePage_Resp.text)
        # 提交登录
        Resp1 = self.r.post(self.url.geturl1('/login'),
                            {"username": username,
                             "password": password,
                             "_csrf": csrf})
        # 获取登录账号的token
        Resp2 = self.r.get(self.url.geturl1('/manage/token'))
        if Resp2.status_code == 200:
            logintoken = "Bearer" + " " + Resp2.text
            # 退出登录
            self.r.get(self.url.geturl1('/logout'))
            log.info(f"获取{username}账号的token成功")
            return logintoken
        else:
            log.error(f"{username}登录未成功,获取{username}的token失败,状态码为:{Resp2.status_code}")

    def creat_singlelogin_school(self, eb, county, livingUrl, name, schoolId, parentSchId):
        """
        创建单点登录学校,只适用单点登录,只会在项目执行之前作为初始前置条件调用一次
        :param eb:
        :param county:
        :param livingUrl:
        :param name:
        :param schoolId:
        :param parentSchId:
        :return:
        """
        resp = self.r.post(url=self.url.geturl1('/schools'),
                           json={"eb": eb, "county": county, "livingUrl": livingUrl, "name": name,
                                 "schoolId": schoolId, "parentSchId": parentSchId},
                           headers={"Authorization": self.roottoken,
                                    "Content-Type": "application/json",
                                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36",
                                    "Accept-Language": "zh-CN,zh;q = 0.9"}
                           )
        if resp.status_code == 200:
            log.info(f"创建{name}成功")
        else:
            log.error(f"创建{name}失败,请排查")
        return resp
